import { store } from '@/store/index';
import { auth } from '@/utils/utils';
import { useIntersectionObserver } from '@vueuse/core';
import defaltImg from '@/assets/icon/weixin-icon.png';

export default {
    debounce: {
        mounted(el, binding) {
            const [fn, event = 'keyup', time = 300] = binding.value;
            let timer;
            el.addEventListener(event, () => {
                timer && clearTimeout(timer);
                // eslint-disable-next-line
                timer = setTimeout(() => fn.apply(null, arguments), time);
            });
        },
        beforeMount(el, binding) {
            const [fn, event = 'keyup'] = binding.value;
            el.removeEventListener(event, fn);
        }
    },
    throttle: {
        mounted(el, binding) {
            const [fn, event = 'keyup', delay = 300] = binding.value;
            let timer = null;
            el.addEventListener(event, () => {
                if (timer) return;
                timer = setTimeout(() => {
                    // eslint-disable-next-line
                    fn.apply(null, arguments);
                    timer = null;
                }, delay);
            });
        },
        beforeMount(el, binding) {
            const [fn, event = 'keyup'] = binding.value;
            el.removeEventListener(event, fn);
        }
    },
    auth: {
        mounted(el, binding) {
            const buttonCode = store.state.menu?.buttonCode || [];
            const code = binding.value;
            // 先注释，等后端菜单接口 button_list 返回后 开启
            if (!auth(buttonCode, code)) {
                el?.parentNode?.removeChild(el);
            }
        }
    },
    tableH: {
        mounted(el) {
            const H = document.body.clientHeight || document.documentElement.clientHeight;
            const h = el?.offsetTop || 0;
            el.style.height = H - h - 140 + 'px';
        }
    },
    imgLazy: {
        mounted(el, binding) {
            const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
                if (isIntersecting) {
                    el.onerror = function () {
                        el.src = defaltImg;
                    };
                    el.src = binding.value;
                    stop();
                }
            });
        }
    }
};
